﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Galoap
{
    public class JSONEncoder
    {

        public Question question { get; set; }

        public JSONEncoder()
        {
            question = null;
        }

        public JSONEncoder(Question q)
        {
            question = q;
        }

        public virtual string GetJSON()
        {

            StringBuilder sb = new StringBuilder();
            /* try
            {
                if (question.AskConfirm)
                {
                    Random r = new Random();

                    // Answer.Load();
                    List<StringAnswer> sal = question.GetAnswersOrderedByFrequency<StringAnswer>();// this.Answer.OrderBy(d => Guid.NewGuid());//GetAnswersOrderedByFrequency<StringAnswer>();
                    int index = r.Next(sal.Count - 1);
                    if (sal.Count >= 5 && r.Next(9) % 3 != 0)
                    {
                        // se ci sono 5 o piu' tipi di risposta, c'è circa il 70% di possibilità di chiedere una question di conferma
                        StringAnswer a = sal.ElementAt(index);
                        sb.Append("\"text\":\"" + question.Text.GetConfirmQuestionText(a.Data) + "\",");
                        sb.Append("\"answer\":\"" + a.Data + "\",");
                    }
                    else
                        sb.Append("\"text\":\"" + question.Text.GetQuestionText() + "\",");

                }
                else
                    sb.Append("\"text\":\"" + question.Text.GetQuestionText() + "\",");
            }
            catch (InvalidOperationException)
            {
                // Console.Error.WriteLine(e.Message);
                // no answer for this question!
                sb.Append("\"text\":\"" + question.Text.GetQuestionText() + "\",");
            } */
            sb.Append("\"text\":\"" + question.Text + "\",");
            sb.Append("\"answer\":\"" + question.MyReply + "\",");
            sb.Append("\"level\":\"" + question.Level + "\",");
            sb.Append("\"questionid\":\"" + question.QuestionID + "\",");
            sb.Append("\"idocument\":[");
            if (question.Document.Count == 0)
                question.Document.Load();
            foreach (Document doc in question.Document)
            {
                sb.Append("\"" + doc.ToString() + "\",");
            }
            if (question.Document.Count > 0) sb.Remove(sb.Length - 1, 1);
            sb.Append("]");
            return sb.ToString();
        }

        public string ExtendJSON(string data)
        {
            return ",\"subclass\":{" + data + "}";
        }

    }
}
